<?php namespace System;


class Model {

    public $db;
    public $error;
    protected $table;
    protected $fields;
    protected $deleted = false;
    protected $id = 'id';

    public function __construct() {
        $config = new \System\Config();
        if ($config->db) {
            $config->load('Database');
            $this->db = new \System\Db($config->mysql);
        } else {
            showError('No database settings');
        }
    }

    function select($select = '*') {
        $this->db->select($select);
        return $this;
    }

    function where($key, $val = '', $operator = null, $or = FALSE, $likeLR = 'both') {
        $this->db->where($key, $val, $operator, $or, $likeLR);
        return $this;
    }

    function join($table, $on, $type = 'left') {
        $this->db->join($table, $on, $type);
        return $this;
    }

    function set($key, $val = null) {
        $this->db->set($key, $val);
        return $this;
    }

    function update($data = null, $where = null) {
        $this->db->update($this->table, $data, $where);
    }

    function get($where = '') {
        if ($where) {
            $this->db->where($where);
        }
        return $this->db->get($this->table)->result();
    }

    function first($where='') {
        if ($where) {
            $this->db->where($where);
        }
        return $this->db->get($this->table)->first();
    }

    function find($id = '') {
        $this->db->table($this->table);
        if ($id) {
            return $this->db->where($this->id, $id)->get()->first();
        } else {
            return $this->db->get()->result();
        }
    }

    function save($data) {
        if ($data[$this->id]) {
            $id = $data[$this->id];
            unset($data[$this->id]);
            $this->db->set($data)->where($this->id, $id)->update($this->table);
        } else {
            $this->db->insert($this->table, $data);
        }
    }

    function lastQuery() {
        return $this->db->lastQuery();
    }

    function delete($id = '') {
        if ($id) {
            $this->db->reset();
            $this->db->where($this->id, $id);
        }
        if ($this->deleted) {
            $this->db->set('deleted', 1)->update($this->table);
        } else {
            $this->db->delete($this->table);
        }
    }

    function dbError() {
        return $this->db->error;
    }

    function error() {
        return $this->error;
    }
}
